#include <jni.h>
#include <fcntl.h>
#include <unistd.h>

#include "../uart/dev_uart.h"
#include "../common/common.h"

#include <android/log.h>
#define TAG "MyJNITag"  // 自定义日志标签
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#include <errno.h>
#include <string.h>

#define SERIAL_PORT "/dev/ttyS2"
#define BAUDRATE B9600 // 9600
#define BUFFER_SIZE 128

extern "C" JNIEXPORT int JNICALL
Java_com_example_bus_AndroidJniControl_openSerial(
        JNIEnv* env, jclass clazz) {
    LOGD("Entering open_serial  1");
    int serial_fd;
    // 打开串口
    serial_fd = open_serial(SERIAL_PORT);
    if (serial_fd < 0) return -1;
    // 配置串口
    if (configure_serial(serial_fd, BAUDRATE) != 0) {
        close_serial(serial_fd);
        return -2;
    }
    return serial_fd;
}


extern "C" JNIEXPORT void JNICALL
Java_com_example_bus_AndroidJniControl_closeSerial(
        JNIEnv* env, jclass clazz, jint serial_fd) {
    LOGD("Entering open_serial  1");

    // 关闭串口
    close_serial(serial_fd);
}

extern "C" JNIEXPORT void JNICALL
Java_com_example_bus_AndroidJniControl_sendSerialData(
        JNIEnv* env, jclass clazz, jint serial_fd,jstring data) {

    // 发送数据
    char *message = jstringToChar(env,data);
    send_data(serial_fd, message);
}

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_bus_AndroidJniControl_receiveSerialData(
        JNIEnv* env, jclass clazz, jint serial_fd) {
    char recv_buffer[BUFFER_SIZE];
    int bytes_received = receive_data(serial_fd, recv_buffer, BUFFER_SIZE - 1);
    if (bytes_received > 0) {
        recv_buffer[bytes_received] = '\0'; // 添加字符串终止符
        printf("Received: %s\n", recv_buffer);
    } else if (bytes_received == 0) {
        printf("No data received.\n");
    }
    return charArrayToJstring(env,recv_buffer);
}


